const path = require('path');
const sqlite3 = require('sqlite3').verbose();
const { app } = require('electron');

class Database {
  constructor() {
    this.dbPath = path.join(app.getPath('userData'), 'abt.db');
    this.db = null;
    this.initialize();
  }

  initialize() {
    const isNew = !require('fs').existsSync(this.dbPath);
    
    this.db = new sqlite3.Database(this.dbPath, (err) => {
      if (err) {
        console.error('数据库连接失败:', err.message);
        return;
      }
      console.log('已连接到数据库:', this.dbPath);
      
      if (isNew) {
        this.initTables();
      }
    });
  }

  initTables() {
    const sql = `
      CREATE TABLE my_table (
        id INTEGER PRIMARY KEY AUTOINCREMENT,
        name TEXT NOT NULL,
        value TEXT,
        created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
      );
    `;
    
    this.db.exec(sql, (err) => {
      if (err) {
        console.error('初始化表结构失败:', err);
      } else {
        console.log('数据库表初始化完成');
      }
    });
  }

  async query(sql, params = []) {
    return new Promise((resolve, reject) => {
      this.db.all(sql, params, (err, rows) => {
        if (err) {
          reject(err);
        } else {
          resolve(rows);
        }
      });
    });
  }

  async run(sql, params = []) {
    return new Promise((resolve, reject) => {
      this.db.run(sql, params, function(err) {
        if (err) {
          reject(err);
        } else {
          resolve({ id: this.lastID, changes: this.changes });
        }
      });
    });
  }

  close() {
    if (this.db) {
      this.db.close();
      console.log('数据库连接已关闭');
    }
  }
}

// 导出单例
module.exports = new Database();